package com.test.qpbgboot.user.controller;

import com.test.qpbgboot.base.response.JsonResult;
import com.test.qpbgboot.user.pojo.dto.AccountLogQuery;
import com.test.qpbgboot.user.pojo.dto.AccountRechargeParam;
import com.test.qpbgboot.user.pojo.vo.PersonalAccountLogVO;
import com.test.qpbgboot.user.pojo.vo.PersonalAccountVO;
import com.test.qpbgboot.user.service.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1/user-account")
@Slf4j
@Api(tags = "user module")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/select/{userId}")
    @ApiOperation(value = "账户信息查询")
    public JsonResult select(@PathVariable @ApiParam(value = "用户id",
    name = "userId",required = true) Long userId) {
        log.debug("账户信息查询:userId={}", userId);
        PersonalAccountVO personalAccount = accountService.accountSelectByUserId(userId);
        return JsonResult.success(personalAccount);
    }

    @GetMapping("/select-log")
    @ApiOperation(value = "账户记录查询")
    public JsonResult selectLog(@ModelAttribute AccountLogQuery accountLogQuery) {
        log.debug("账户记录查询:accountLogQuery={}", accountLogQuery);
        List<PersonalAccountLogVO> accountLogList = accountService.accountLogSelect(accountLogQuery);
        return JsonResult.success(accountLogList);
    }

    @GetMapping("/recharge")
    @ApiOperation(value = "账户充值")
    public void recharge(@Valid @ModelAttribute AccountRechargeParam accountRechargeParam,
                         @ApiIgnore HttpServletResponse response) throws IOException {
        log.debug("账户充值:accountRechargeParam={}", accountRechargeParam);
        String formPayStr = accountService.accountRecharge(accountRechargeParam);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(formPayStr);
        writer.flush();
        writer.close();
    }

    @PostMapping("/recharge/notify")
    @ApiOperation(value = "账户充值支付宝通知")
    public void rechargeNotify(@RequestParam Map<String, String> params) {
        log.debug("账户充值支付宝通知:params={}", params);
        accountService.accountRechargeNotify(params);
    }
}
